<template>
  <el-dialog
    :title="id ? '修改账号' : '新增账号'"
    :visible.sync="dialogFormVisible"
    :append-to-body="true"
    :close-on-click-modal="false"
    width="600px"
    @open="handleDialogOpen"
  >
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="temp"
      label-position="left"
      label-width="100px"
      style="margin: 0 30px"
    >
      <template>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="temp.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="用户角色" prop="role_id">
          <el-radio-group
            v-model="temp.role_id"
            style="display: flex; align-items: center; flex-wrap: wrap"
            @change="handleRoleChange"
          >
            <el-radio
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.id"
              style="height: 32px; display: flex; align-items: center"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="绑定景区" prop="attraction_ids">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
            >全部景区</el-checkbox
          >
          <el-checkbox-group
            v-model="temp.attraction_ids"
            @change="handleCheckedCitiesChange"
            style="margin-left: 20px"
          >
            <el-checkbox
              v-for="item in attractionOptions"
              :key="item.id"
              :label="item.id"
              :name="item.id"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 修改区域选择逻辑，允许为每个景区设置区域 -->
        <el-form-item
          v-if="temp.attraction_ids.length > 0"
          label="景区区域设置"
          prop="attraction_parts"
        >
          <div
            v-for="attractionId in temp.attraction_ids"
            :key="'attraction-' + attractionId"
            style="margin-bottom: 10px; display: flex; align-items: center"
          >
            <template v-if="getPartsForAttraction(attractionId).length > 0">
              <div style="margin-bottom: 5px; width: 140px">
                {{ getAttractionNameById(attractionId) }}
              </div>
              <el-select
                v-model="attractionPartsMapping[attractionId]"
                placeholder="请选择区域"
                @change="(value) => handlePartChangeForAttraction(attractionId, value)"
              >
                <el-option
                  v-for="item in getPartsForAttraction(attractionId)"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </template>
            <template v-else>
              <div style="margin-bottom: 5px; width: 140px">
                {{ getAttractionNameById(attractionId) }}
              </div>
              <div style="color: #909399; font-size: 14px">该景区暂无可选区域</div>
            </template>
          </div>
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="saveData">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getDetail, add, edit } from '@/api/account'
import { getList as getAttractionList } from '@/api/attraction'
import { getList as getRoleList } from '@/api/roles'
const rule = [{ required: true, message: '必填项不能为空' }]
export default {
  name: 'AccountEdit',

  data() {
    return {
      dialogFormVisible: false,
      id: '',
      temp: {
        name: '',
        mobile: '',
        password: '',
        role_id: '',
        attraction_ids: [],
        // 移除旧的字段结构
        // part_prop_id: '',
        // attraction_part_info: {
        //   attraction_id: '',
        //   part_id: ''
        // },
        // attraction_parts_mapping: {}
        attraction_parts: [] // 新的数据结构
      },

      checkAll: false,
      isIndeterminate: true,
      rules: {
        name: rule,
        mobile: rule,
        password: rule,
        role_id: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
        attraction_ids: [{ required: true, message: '请选择景区', trigger: 'change' }]
      },
      roleOptions: [],
      attractionOptions: [],
      attractionPartsMap: {}, // 存储每个景区的区域列表
      isAdmin: false, // 是否为超级管理员
      attractionPartsMapping: {} // 用于UI展示的映射关系
    }
  },

  created() {
    getAttractionList({ page: 1, size: 1000 }).then((res) => {
      this.attractionOptions = res.data.list_data
    })
    getRoleList({ page: 1, size: 1000 }).then((res) => {
      this.roleOptions = res.data.list_data
      // 检查当前用户是否为超级管理员
      // this.checkIsAdmin()
    })
  },
  methods: {
    handleDialogOpen() {
      this.$nextTick(() => {
        const firstInput = this.$el.querySelector('input')
        if (firstInput) {
          firstInput.focus()
        }
      })
    },
    handleRoleChange(value) {
      // 查找roleOptions中id===value的name
      const selectedRole = this.roleOptions.find((role) => role.id === value)
      if (selectedRole) {
        console.log('选中的角色名称:', selectedRole.name)
        // 判断是否为超级管理员角色
        this.isAdmin = selectedRole.name === '超级管理员' || value === 1
      }
    },

    handleCreate() {
      this.id = ''
      this.temp = {
        name: '',
        mobile: '',
        password: '',
        role_id: '',
        attraction_ids: [],
        attraction_parts: []
      }
      this.attractionPartsMapping = {}
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },

    // 编辑
    handleEdit(id) {
      getDetail(id).then((res) => {
        this.id = id
        const data = res.data

        // 基础数据赋值
        this.temp.name = data.name
        this.temp.mobile = data.mobile
        this.temp.role_id = data.role_id
        this.temp.attraction_ids = data.attraction_ids || []
        this.temp.attraction_parts = data.attraction_parts || []

        // 处理角色信息
        this.handleRoleChange(data.role_id)

        // 初始化景区-区域映射用于UI展示
        this.attractionPartsMapping = {}
        if (data.attraction_parts && data.attraction_parts.length > 0) {
          data.attraction_parts.forEach((part) => {
            this.$set(this.attractionPartsMapping, part.attraction_id, part.part_id)
          })
        }

        // 加载所有选中景区的区域数据
        this.temp.attraction_ids.forEach((attractionId) => {
          this.loadPartsForAttraction(attractionId)
        })

        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      })
    },

    handleCheckAllChange(val) {
      this.temp.attraction_ids = val ? this.attractionOptions.map((item) => item.id) : []
      this.isIndeterminate = false

      // 清空区域映射
      this.attractionPartsMapping = {}
      this.temp.attraction_parts = []

      // 如果选择了景区，加载每个景区的区域
      if (val) {
        this.temp.attraction_ids.forEach((attractionId) => {
          this.loadPartsForAttraction(attractionId)
        })
      }
    },

    handleCheckedCitiesChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.attractionOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.attractionOptions.length

      // 更新区域映射，移除未选中的景区
      const newMapping = {}
      Object.keys(this.attractionPartsMapping).forEach((attractionId) => {
        if (value.includes(parseInt(attractionId)) || value.includes(attractionId)) {
          newMapping[attractionId] = this.attractionPartsMapping[attractionId]
        }
      })
      // 使用新对象替换旧对象，确保Vue能检测到变化
      this.attractionPartsMapping = newMapping

      // 更新attraction_parts，移除未选中的景区
      this.temp.attraction_parts = this.temp.attraction_parts.filter(
        (part) => value.includes(parseInt(part.attraction_id)) || value.includes(part.attraction_id)
      )

      // 加载新选中景区的区域
      value.forEach((attractionId) => {
        if (!this.attractionPartsMap[attractionId]) {
          this.loadPartsForAttraction(attractionId)
        }
      })
    },

    // 加载指定景区的区域列表
    loadPartsForAttraction(attractionId) {
      const attraction = this.attractionOptions.find((item) => item.id === attractionId)
      if (attraction && attraction.part_props && attraction.part_props.length > 0) {
        this.attractionPartsMap[attractionId] = attraction.part_props.map((item, index) => {
          return {
            id: index + 1,
            name: item
          }
        })
      } else {
        this.attractionPartsMap[attractionId] = []
        // // 添加提示消息
        // const attractionName = attraction ? attraction.name : '未知景区'
        // this.$message({
        //   message: `${attractionName}暂无可选区域`,
        //   type: 'warning',
        //   duration: 2000
        // })
      }
    },

    // 获取指定景区的区域列表
    getPartsForAttraction(attractionId) {
      return this.attractionPartsMap[attractionId] || []
    },

    // 获取景区名称
    getAttractionNameById(attractionId) {
      const attraction = this.attractionOptions.find((item) => item.id === attractionId)
      return attraction ? attraction.name : '未知景区'
    },

    // 处理区域变更
    handlePartChangeForAttraction(attractionId, partId) {
      console.log('attractionId:', attractionId, 'partId:', partId)
      // 使用Vue的$set方法确保响应式更新
      this.$set(this.attractionPartsMapping, attractionId, partId)

      // 更新attraction_parts数组
      const existingIndex = this.temp.attraction_parts.findIndex(
        (part) => part.attraction_id === attractionId
      )

      if (existingIndex >= 0) {
        // 更新现有记录
        this.temp.attraction_parts[existingIndex].part_id = partId
      } else {
        // 添加新记录
        this.temp.attraction_parts.push({
          attraction_id: attractionId,
          part_id: partId
        })
      }
    },

    // 保存
    saveData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const d = JSON.parse(JSON.stringify(this.temp))

          // 确保attraction_parts数据完整
          d.attraction_parts = d.attraction_ids
            .map((attractionId) => {
              const existingPart = d.attraction_parts.find(
                (part) => part.attraction_id === attractionId
              )
              if (existingPart) {
                return existingPart
              }
              return {
                attraction_id: attractionId,
                part_id: this.attractionPartsMapping[attractionId] || 0
              }
            })
            .filter((part) => part.part_id)

          console.log('提交数据:', d)
          const p = this.id ? edit(this.id, d) : add(d)
          p.then(() => {
            this.$parent.fetchData()
            this.dialogFormVisible = false
            this.$parent.$notify({
              title: '成功',
              message: this.id ? '修改成功' : '添加成功',
              type: 'success'
            })
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.item-p {
  margin: 0;
  /* height: 1px; */
}
</style>
